package config

import (
	"os"
	"strconv"

	"github.com/joho/godotenv"
)

type Config struct {
	// 服务器配置
	ServerHost string
	ServerPort string
	Environment string

	// 数据库配置
	DBHost     string
	DBPort     string
	DBUsername string
	DBPassword string
	DBName     string

	// Redis配置
	RedisHost     string
	RedisPort     string
	RedisPassword string
	RedisDB       int

	// 微信小程序配置
	WechatAppID     string
	WechatSecret    string
	WechatMchID     string
	WechatAPIKey    string
	WechatCertPath  string
	WechatKeyPath   string

	// JWT配置
	JWTSecret      string
	JWTExpireHours int

	// 日志配置
	LogLevel string
	LogFile  string
}

func LoadConfig() *Config {
	// 加载环境变量文件
	godotenv.Load("config.env")

	return &Config{
		// 服务器配置
		ServerHost:  getEnv("SERVER_HOST", "0.0.0.0"),
		ServerPort:  getEnv("SERVER_PORT", "8080"),
		Environment: getEnv("ENVIRONMENT", "production"),

		// 数据库配置
		DBHost:     getEnv("DB_HOST", "localhost"),
		DBPort:     getEnv("DB_PORT", "3307"),
		DBUsername: getEnv("DB_USERNAME", "root"),
		DBPassword: getEnv("DB_PASSWORD", "password"),
		DBName:     getEnv("DB_NAME", "jianianhua"),

		// Redis配置
		RedisHost:     getEnv("REDIS_HOST", ""),
		RedisPort:     getEnv("REDIS_PORT", "6379"),
		RedisPassword: getEnv("REDIS_PASSWORD", ""),
		RedisDB:       getEnvAsInt("REDIS_DB", 0),

		// 微信小程序配置
		WechatAppID:    getEnv("WECHAT_APPID", ""),
		WechatSecret:   getEnv("WECHAT_SECRET", ""),
		WechatMchID:    getEnv("WECHAT_MCHID", ""),
		WechatAPIKey:   getEnv("WECHAT_API_KEY", ""),
		WechatCertPath: getEnv("WECHAT_CERT_PATH", "./certs/apiclient_cert.pem"),
		WechatKeyPath:  getEnv("WECHAT_KEY_PATH", "./certs/apiclient_key.pem"),

		// JWT配置
		JWTSecret:      getEnv("JWT_SECRET", "your_jwt_secret_key"),
		JWTExpireHours: getEnvAsInt("JWT_EXPIRE_HOURS", 24),

		// 日志配置
		LogLevel: getEnv("LOG_LEVEL", "info"),
		LogFile:  getEnv("LOG_FILE", "./logs/app.log"),
	}
}

func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

func getEnvAsInt(key string, defaultValue int) int {
	if value := os.Getenv(key); value != "" {
		if intValue, err := strconv.Atoi(value); err == nil {
			return intValue
		}
	}
	return defaultValue
}
